package com.wasu.utils;

import android.annotation.SuppressLint;
import android.text.TextUtils;

import com.wasu.doicommon.util.LogUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * <p>------------------------------------------------------
 * <p>Copyright (C) 2018 wasu company, All rights reserved.
 * <p>------------------------------------------------------
 * <p> 有关于处理时间的工具类
 * <p>
 *
 * @author Created by TongBing
 * @date on 2018/6/30.
 */
public class TimeUtil {
    private static final String TAG = TimeUtil.class.getSimpleName();

    private static final String DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss";
    public static final String DEFAULT_FORMAT2 = "yyyy-MM-dd HH:mm";
    public static final String DEFAULT_FORMAT3 = "yyyy-MM-dd";

    /**
     * 将年月日分开
     *
     * @param date String
     * @return
     */
    public static String splitDateString(String date) {
        LogUtils.e(TAG, "splitDateString=" + date);

        String[] str = date.split("-");
        String returnStr = "";
        if (null != str[1] && null != str[2]) {
            if (str[2].contains(" ")) {
                str[2] = str[2].split(" ")[0];
            }
            if (str[1].startsWith("0")) {
                str[1] = str[1].substring(1);
            }
            if (str[2].startsWith("0")) {
                str[2] = str[2].substring(1);
            }
            returnStr = str[1] + "月" + str[2] + "日";
        }

        return returnStr;
    }


    /**
     * 将时间后面的时分分开
     *
     * @param date
     * @return
     */
    public static String splitTimeString(String date) {
        String[] str = date.split(" ");
        String returnStr = "";
        if (null != str[1]) {
            if (str[1].contains(":")) {
                String[] timeStr = str[1].split(":");
                if (timeStr[0].startsWith("0") && timeStr[0].endsWith("0")) {
                    timeStr[0] = timeStr[0];
                } else if (!timeStr[0].startsWith("0")) {
                    timeStr[0] = timeStr[0];
                } else {
                    timeStr[0] = timeStr[0].substring(1);
                }

                returnStr = timeStr[0] + ":" + timeStr[1];

            }

        }

        return returnStr;
    }

    /**
     * 将年月日分开
     *
     * @param date
     * @return
     */
    public static String splitTimeYear(String date) {
        String[] str = date.split(" ");
        String returnStr = "";
        if (null != str[0]) {
            return str[0];
        }

        return returnStr;
    }

    /***
     * 日期格式转换
     * @param time 时间
     * @param format1 原格式
     * @param format2 目标格式
     * @return
     */
    public static String parseTime(String time, String format1, String format2) {
        return formatTime(parseTime(time, format1), format2);
    }

    /**
     * 将时间解析为毫秒值
     *
     * @param time   String
     * @param format String
     * @return long
     */
    @SuppressLint("SimpleDateFormat")
    public static long parseTime(String time, String format) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        try {
            return simpleDateFormat.parse(time).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }


    /**
     * 将时间解析为毫秒值
     * 时间格式为默认格式 yyyy-MM-dd HH:mm:ss
     *
     * @param time String
     * @return long
     */
    public static long parseTime(String time) {
        return parseTime(time, DEFAULT_FORMAT);
    }

    /**
     * 格式化时间
     *
     * @param time   long
     * @param format String
     * @return String
     */
    @SuppressLint("SimpleDateFormat")
    public static String formatTime(long time, String format) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        return simpleDateFormat.format(time);
    }

    /**
     * 获取系统时间
     *
     * @return 字符串yyyy-MM-dd HH:mm:ss
     */

    public static String getCurrentDate() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());
        return formatter.format(curDate);
    }

    /**
     * 获取日期yyyy-MM-dd
     *
     * @return yyyy-MM-dd
     */
    public static String getDate() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        return formatter.format(new Date());
    }

    /**
     * 按照格式yyyy-MM-dd HH:mm返回string
     *
     * @param dateTime 日期字符串
     * @return yyyy-MM-dd HH:mm
     */
    public static String getFormatStringTime(String dateTime) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date date = null;
        try {
            date = formatter.parse(dateTime);
        } catch (ParseException e) {
            LogUtils.eTag(TAG, e.toString());
        }
        return formatter.format(date);
    }

    /**
     * 按照格式yyyy-MM-dd返回string
     *
     * @param dateTime 日期字符串
     * @return yyyy-MM-dd
     */
    public static String getFormatTimeString(String dateTime) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = formatter.parse(dateTime);
        } catch (ParseException e) {
            LogUtils.eTag(TAG, e.toString());
        }
        return formatter.format(date);
    }

    /**
     * 按照格式HH:mm返回string，只返回 时分
     *
     * @param dateTime 日期字符串
     * @return 时分HH:mm
     */
    public static String getFormatStringDate(String dateTime) {
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
        SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = formatter1.parse(dateTime);
        } catch (ParseException e) {
            LogUtils.eTag(TAG, e.toString());
            return "";
        }
        return formatter.format(date);
    }

    /**
     * 按照格式HH:mm返回string，只返回 时分
     *
     * @return 当前时间的时分HH:mm
     */
    public static String getFormatCurrentTime() {
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
        return formatter.format(new Date());
    }

    /**
     * 根据输入日期字符串，返回友好格式的日期字符串
     *
     * @return 今天 HH:mm:ss 或者原数据
     */
    public static String getFriendlyCurrentDate(String dateTime) {
        if (dateTime == null) {
            return "";
        }
        dateTime = getFormatStringTime(dateTime);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        try {

            Date date = formatter.parse(dateTime);
            Date current = formatter.parse(getDate());
            Date tomorrow = formatter.parse(getTomorrow());
            Date yesterday = formatter.parse(getYesterday());
            if (date.compareTo(current) == 0) {
                dateTime = dateTime.replace(formatter.format(current), "今天");
            } else if (date.compareTo(tomorrow) == 0) {
                dateTime = dateTime.replace(formatter.format(tomorrow), "明天");
            } else if (date.compareTo(yesterday) == 0) {
                dateTime = dateTime.replace(formatter.format(yesterday), "昨天");
            }

        } catch (ParseException e) {
            LogUtils.eTag(TAG, e.toString());
            return "";
        }
        return dateTime;
    }

    /**
     * 比较两个日期字符串 如果time1早于time2返回true，否则返回false
     *
     * @param time1 time1
     * @param time2 time2
     * @return 如果time1早于time2返回true，否则返回false
     * @throws ParseException 解析异常
     */
    public static boolean compareDateString(String time1, String time2) throws ParseException {

        if (time1 == null || time2 == null) {
            return false;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date a = sdf.parse(time1);
        Date b = sdf.parse(time2);
        return a.before(b);
    }

    /**
     * 通过毫秒数获取时间HH:mm:ss
     *
     * @param time 毫秒数
     * @return 时分 HH:mm:ss
     */
    public static String getStringDateFromLong(long time) {
        Date date = new Date();
        date.setTime(time);
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
        return formatter.format(date);
    }

    /**
     * 通过毫秒数获取时间yyyy-MM-dd HH:mm:ss
     *
     * @param time 毫秒数
     * @return String : yyyy-MM-dd HH:mm:ss
     */
    public static String getStringFromLong(long time) {
        Date date = new Date();
        date.setTime(time);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");
        return formatter.format(date);
    }

    /**
     * 通过毫秒数获取时间 M月d日
     *
     * @param time 毫秒数
     * @return String : M月d日
     */
    public static String getMonthDayFromLong(long time) {
        Date date = new Date();
        date.setTime(time);
        SimpleDateFormat formatter = new SimpleDateFormat("M月d日");
        return formatter.format(date);
    }

    /**
     * 根据时分秒字符串得到一个日历对象
     *
     * @param hour
     * @param min
     * @param sec
     * @return Calendar
     */
    public static Calendar getCalendarFromString(String hour, String min, String sec) {
        Calendar calendar = null;
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        try {
            Date date = sdf.parse(hour + ":" + min + ":" + sec);
            if (date != null) {
                calendar = Calendar.getInstance();
                calendar.setTime(date);
            }
        } catch (ParseException e) {
            LogUtils.eTag(TAG, e.toString());
        }
        return calendar;
    }

    /**
     * 根据日历得到一个字符串HH:mm:ss
     *
     * @param calendar Calendar
     * @return HH:mm:ss
     */
    public static String getStringDateFromCalendar(Calendar calendar) {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        return sdf.format(calendar.getTime());
    }

    /**
     * 取前一个小时的时间
     *
     * @return HH:mm
     */
    public static String beforeOneHourToNowDate() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - 1);
        SimpleDateFormat df = new SimpleDateFormat("HH:mm");
        return df.format(calendar.getTime());
    }

    /**
     * 取得当前时间之后一个小时
     *
     * @return HH:mm
     */
    public static String afterOneHourToNowDate() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) + 1);
        SimpleDateFormat df = new SimpleDateFormat("HH:mm");
        return df.format(calendar.getTime());
    }

    /**
     * 明天
     *
     * @return yyyy-MM-dd
     */
    public static String getTomorrow() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        return df.format(calendar.getTime());
    }

    /**
     * 昨天
     *
     * @return yyyy-MM-dd
     */
    public static String getYesterday() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        return df.format(calendar.getTime());
    }

    /**
     * 十四天前，格式为yyyy-MM-dd HH:mm:ss
     *
     * @return yyyy-MM-dd HH:mm:ss
     */
    public static String getFourteenDaysAgo() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, -14);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return df.format(calendar.getTime());
    }

    /**
     * 十四天前，格式为yyyy-MM-dd
     *
     * @return yyyy-MM-dd
     */
    public static String getFormatFourteenDaysAgo() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, -14);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        return df.format(calendar.getTime());
    }

    /**
     * 时间转换为时分秒
     *
     * @param ms
     * @return
     */
    public static String formatTime(Long ms) {
        Integer ss = 1000;
        Integer mi = ss * 60;
        Integer hh = mi * 60;
        Integer dd = hh * 24;

        Long day = ms / dd;
        Long hour = (ms - day * dd) / hh;
        Long minute = (ms - day * dd - hour * hh) / mi;
        Long second = (ms - day * dd - hour * hh - minute * mi) / ss;
        Long milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss;

        StringBuffer sb = new StringBuffer();
        if (day > 0) {
            sb.append(day + "天");
        }
        if (hour > 0) {
            sb.append(hour + "小时");
        }
        if (minute > 0) {
            sb.append(minute + "分");
        }
        if (second > 0) {
            sb.append(second + "秒");
        }
        if (milliSecond > 0) {
            sb.append(milliSecond + "毫秒");
        }
        return sb.toString();
    }

    /**
     * 时间转换为时分秒
     *
     * @param ms
     * @return
     */
    public static String formatTime(long ms) {

        int ss = 1000;
        int mi = ss * 60;
        int hh = mi * 60;
        int dd = hh * 24;

        long day = ms / dd;
        long hour = (ms - day * dd) / hh;
        long minute = (ms - day * dd - hour * hh) / mi;
        long second = (ms - day * dd - hour * hh - minute * mi) / ss;
        long milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss;

        String strDay = day < 10 ? "0" + day : "" + day; //天
        String strHour = hour < 10 ? "0" + hour : "" + hour;//小时
        String strMinute = minute < 10 ? "0" + minute : "" + minute;//分钟
        String strSecond = second < 10 ? "0" + second : "" + second;//秒
        String strMilliSecond = milliSecond < 10 ? "0" + milliSecond : "" + milliSecond;//毫秒
        strMilliSecond = milliSecond < 100 ? "0" + strMilliSecond : "" + strMilliSecond;

        return strHour + ":" + strMinute + ":" + strSecond;
    }

    /**
     * 时间转换为时
     *
     * @param ms
     * @return
     */
    public static String formatTimeToHour(Long ms) {
        Integer ss = 1000;
        Integer mi = ss * 60;
        Integer hh = mi * 60;
        Integer dd = hh * 24;

        Long day = ms / dd;
        Long hour = (ms - day * dd) / hh;
        Long minute = (ms - day * dd - hour * hh) / mi;
        Long second = (ms - day * dd - hour * hh - minute * mi) / ss;
        Long milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss;

        StringBuffer sb = new StringBuffer();
        if (day > 0) {
            sb.append(day + "天");
        }
        if (hour > 0) {
            sb.append(hour + "小时");
        }
        if (minute > 0) {
            sb.append(minute + "分");
        }
        if (second > 0) {
            sb.append(second + "秒");
        }
        if (milliSecond > 0) {
            sb.append(milliSecond + "毫秒");
        }
        return sb.toString();
    }

    /**
     * 倒计时显示
     *
     * @param s 单位秒（秒）
     * @return d天h时m分s秒
     */
    public static String time2CountSecond(long s) {
        if (s < 0) {
            return "";
        }
        int remainder;
        int day = (int) (s / (3600 * 24));
        remainder = (int) (s % (3600 * 24));
        int hour = remainder / 3600;
        remainder = remainder % 3600;
        int minute = remainder / 60;
        remainder = remainder % 60;
        StringBuilder sb = new StringBuilder();
        if (day > 0) {
            sb.append(day).append("天");
        }
        if (String.valueOf(hour).length() < 2) {
            sb.append(0);
        }
        sb.append(hour).append("时");
        if (String.valueOf(minute).length() < 2) {
            sb.append(0);
        }
        sb.append(minute).append("分");
        if (String.valueOf(remainder).length() < 2) {
            sb.append(0);
        }
        sb.append(remainder).append("秒");
        return sb.toString();
    }

    /**
     * 距离倒计时结束剩余秒数
     *
     * @param time yyyy-MM-dd HH:mm:ss
     * @return 时间（秒）
     */
    @SuppressLint("SimpleDateFormat")
    public static long getCountDownTime(String time) {
        if (TextUtils.isEmpty(time)) {
            return 0;
        }
        SimpleDateFormat formatter = new SimpleDateFormat(DEFAULT_FORMAT);
        try {
            return (formatter.parse(time).getTime() - System.currentTimeMillis()) / 1000;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 时间转换为时
     *
     * @param ms
     * @return
     */
    public static String formatTimeToHour(long ms) {
        int ss = 1000;
        int mi = ss * 60;
        int hh = mi * 60;

        long hour = ms / hh;

        StringBuffer sb = new StringBuffer();
        sb.append(hour + "小时");

        return sb.toString();
    }

    /**
     * 比较时间是否在开始和结束范围内
     *
     * @param currentDate
     * @param startTime
     * @param endTime
     * @return
     * @throws ParseException
     */
    public static boolean compare(Date currentDate, String startTime, String endTime) throws ParseException {
        //如果想比较日期则写成"yyyy-MM-dd"就可以了
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        //将字符串形式的时间转化为Date类型的时间
        Date a = sdf.parse(startTime);
        Date b = sdf.parse(endTime);
        //Date类的一个方法
        return a.before(currentDate) && b.after(currentDate);
    }

    /**
     * 产生某范围的随机数
     *
     * @param count
     * @return
     */
    public static int getRandom(int count) {
        if (count == 0) {
            return 0;
        }
        java.util.Random random = new java.util.Random();
        long randomLong = Math.abs(random.nextInt());
        int index = (int) (randomLong % count);
        LogUtils.dTag("abc", "----产生的随机数 = " + index);
        return index;
    }

}
